<?php
/**
 * Created by PhpStorm.
 * User: hisheng
 * Date: 2017/6/5
 * Time: 16:35
 */
namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Loan;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Input;

class LoanController extends Controller
{
    public $loan;
    public function __construct(Loan $loan)
    {
        $this->loan = $loan;
    }
    
    //贷款列表页
    public function index(){
        $loans = Loan::orderBy('updated_at','desc')->where('is_delete',0)->get();
        return view('loan.index',compact('loans'));
    }
    //增加页面
    public function add(){
        return view('admin.loan.add');
    }
    
    public function postAdd(){
         $id = Input::get('id',0);
         if($id){
             $this->loan = $this->loan->find($id);
         }
         
        $this->insertDefault('company_name');
        $this->insertDefault('loan_url');
        $this->insertDefault('provision');
        $this->insertDefault('apply');
        $this->insertDefault('feature');
        $this->insertDefault('min_amount');
        $this->insertDefault('max_amount');
        $this->insertDefault('min_days');
        $this->insertDefault('max_days');
        $this->insertDefault('name');
        $this->insertDefault('phone');
        $this->insertDefault('rate');
        $this->insertDefault('rate_type');
        $this->insertDefault('job');
        $this->insertDefault('success_rate');
        $this->insertFile('icon');
        $this->insertMonthRate();
        $this->loan->apply_number = rand(600000,700000);
        $this->loan->save();
        return redirect('/admin/loans');
    }
    
    public function edit($id){
        $loan = $this->loan->find($id);
        if($loan){
            return view('admin.loan.edit',compact('loan'));
        }
    }
    
    public function down($id){
        $loan = $this->loan->find($id);
        if($loan){
            $loan->is_delete = 1;
            $loan->save();
        }
        return redirect('/admin/loans');
    }
    
    public function insertMonthRate(){
        $rate_type = $this->loan->rate_type;
        if(empty($rate_type)){
            throw new \Exception('缺少rate_type');
        }
        $month_rate = '';
        if($rate_type == 'day'){
            $month_rate = $this->loan->rate * 30;
        }
        if($rate_type == 'month'){
            $month_rate = $this->loan->rate ;
        }
        
        if($month_rate){
            $this->loan->month_rate = $month_rate;
        }
        
        
    }
    
    public function insertDefault($name){
        $v = Input::get($name);
        if($name){
            $this->loan->$name = $v;
        }
    }
    public function insertFile($name){
        $avatar = $this->saveFile($name);
        if($avatar){
            $this->loan->icon = $avatar;
        }
    }
    
    
    
    
}